package com.notary.tx_live_plugin.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.notary.tx_live_plugin.util.ChatManager;
import com.notary.tx_live_plugin.util.TxLogger;
import com.notary.tx_live_plugin.util.TxConstant;
import com.tencent.liteav.meetings.MeetingPageLayoutManager;
import com.tencent.liteav.meetings.MeetingVideoView;
import com.tencent.liteav.meetings.MemberEntity;
import com.tencent.liteav.meetings.MemberListAdapter;
import com.tencent.liteav.meetings.TRTCMeeting;
import com.tencent.liteav.meetings.TRTCMeetingCallback;
import com.tencent.liteav.meetings.TRTCMeetingDef;
import com.tencent.liteav.meetings.TRTCMeetingDelegate;
import com.tencent.trtc.TRTCCloudDef;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 视频聊天
 */
public class TxLiveChatMeetView extends FrameLayout implements TRTCMeetingDelegate {

    public TxLiveChatMeetView(@NonNull Context context) {
        super(context);
        init(context);
    }

    public TxLiveChatMeetView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public TxLiveChatMeetView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    //所有在会议中的视频列表
    private RecyclerView mListRv;
    //视频item双击后全屏显示，显示双击后移除全屏显示
    private FrameLayout mContainerFl;
    private MeetingVideoView mViewVideo;
    private TRTCMeeting mTRTCMeeting;
    private List<MemberEntity> mMemberEntityList;
    private MemberListAdapter mMemberListAdapter;
    private Map<String, MemberEntity> mStringMemberEntityMap;
    private List<MemberEntity> mVisibleVideoStreams;

    private boolean isCreating = false;
    private boolean mIsUserEnterMuteAudio = false; //后续人员进入都进入静音模式
    private boolean isFrontCamera = true;
    private boolean isUseSpeaker = true;
    // 是否打开音量提示
    private boolean mAudioVolumeEvaluation = true;
    private boolean mOpenAudio = true;
    private String mShowUserId = "";
    private int mRoomId;
    private String mUserId;
    private int mSdkAppId;
    private String mUserSign;

    private final MeetingVideoView.Listener mMeetingViewClick = this::onDoubleClick;
    private ChatManager.OnChatCallback mOnChatCallback;

    private void init(Context context) {
        mListRv = new RecyclerView(context);
        mContainerFl = new FrameLayout(context);
        addView(mListRv, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        addView(mContainerFl, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    public void initChatView(){
        if(mRoomId != 0 && mUserId != null && mUserSign != null && mSdkAppId != 0){
            startCharMeet(mSdkAppId,mUserId,mUserSign,mRoomId);
        }
    }

    /**
     * 开启 视频聊天会议
     *
     * @param sdkAppId sdk申请的appId
     * @param userId   标志用户唯一
     * @param userSign 用户签名
     */
    public void startCharMeet(int sdkAppId, String userId, String userSign,int roomId) {
        initData(sdkAppId, userId, userSign,roomId);
        initView();
        mTRTCMeeting.login(sdkAppId, userId, userSign, new TRTCMeetingCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                TxLogger.d("is login success", code == 0, "code", code, "msg", msg);
                if (code != 0) {
                    toast("登录房间失败："+ code + msg);
                    //ToastUtil.showMsg("登录房间失败："+ code + msg);
                    return;
                }
                startCreateOrEnterMeeting();
            }
        });
    }

    public boolean isCreating(){
        return isCreating;
    }
    public boolean isOpenAudio(){
        return mOpenAudio;
    }

    /**
     * 退出房间
     */
    public void stopChat(){
        exitMeetingConfirm();
    }

    /**
     * 切换 开启音频
     */
    public Boolean switchAudio(){
        if(mTRTCMeeting == null) return null;
        boolean isAudioOn = mOpenAudio;
        if (isAudioOn) {
            mTRTCMeeting.stopMicrophone();
        } else {
            mTRTCMeeting.startMicrophone();
        }
        mOpenAudio = !isAudioOn;
        return mOpenAudio;
    }

    public void onDestroy(){
        if(mTRTCMeeting != null) {
            exitMeetingConfirm();
            mTRTCMeeting.setDelegate(null);
            mTRTCMeeting.stopCameraPreview();
        }
        mTRTCMeeting = null;
    }

    /**
     * 初始化数据
     */
    private void initData(int sdkAppId, String userId, String userSign,int roomId) {
        mUserId = userId;
        mRoomId = roomId;
        mSdkAppId = sdkAppId;
        mUserSign = userSign;
        mTRTCMeeting = TRTCMeeting.sharedInstance(getContext());
        mTRTCMeeting.initAppId(sdkAppId, userId, userSign);

        mStringMemberEntityMap = new HashMap<>();
        mMemberEntityList = new ArrayList<>();

        //创建自己的 MemberEntity
        MemberEntity entity = new MemberEntity();
        MeetingVideoView meetingVideoView = new MeetingVideoView(getContext());
        meetingVideoView.setSelfView(true);
        meetingVideoView.setMeetingUserId(userId);
        meetingVideoView.setListener(mMeetingViewClick);
        meetingVideoView.setNeedAttach(true);
        entity.setMeetingVideoView(meetingVideoView);
        entity.setShowAudioEvaluation(mAudioVolumeEvaluation);
        entity.setAudioAvailable(true);
        entity.setVideoAvailable(true);
        entity.setMuteAudio(false);
        entity.setMuteVideo(false);
        entity.setUserId(userId);
        entity.setUserName("mUserName");
        entity.setUserAvatar("mUserAvatar");
        addMemberEntity(entity);
    }

    /**
     * 初始化视频
     */
    private void initView() {
        mViewVideo = mMemberEntityList.get(0).getMeetingVideoView();
        mMemberListAdapter = new MemberListAdapter(getContext(), mTRTCMeeting, mMemberEntityList, null);

        mListRv.setHasFixedSize(true);
        MeetingPageLayoutManager pageLayoutManager = new MeetingPageLayoutManager(2, 2, MeetingPageLayoutManager.HORIZONTAL);
        pageLayoutManager.setAllowContinuousScroll(false);
        pageLayoutManager.setPageListener(new MeetingPageLayoutManager.PageListener() {
            @Override
            public void onPageSizeChanged(int pageSize) {
            }

            @Override
            public void onPageSelect(int pageIndex) {
            }

            @Override
            public void onItemVisible(int fromItem, int toItem) {
                TxLogger.d("onItemVisible: " + fromItem + " to " + toItem+" memberSize "+mMemberEntityList.size());
                if (toItem == mMemberEntityList.size() - 1) {
                    //最后一个是自己的video，分开处理
                    processSelfVideoPlay(toItem);
                    processVideoPlay(fromItem, toItem - 1);
                } else {
                    processVideoPlay(fromItem, toItem);
                }
            }
        });
        mListRv.setLayoutManager(pageLayoutManager);
        mListRv.setAdapter(mMemberListAdapter);
        PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(mListRv);
        // 注册本地变更的通知
//        IntentFilter intentFilter = new IntentFilter(AUDIO_EVALUATION_CHANGED);
//        LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
//            @Override
//            public void onReceive(Context context, Intent intent) {
//                boolean isAudioVolumeEvaluationShow = mAudioVolumeEvaluation;
//                for (MemberEntity entity : mMemberEntityList) {
//                    entity.setShowAudioEvaluation(isAudioVolumeEvaluationShow);
//                }
//                mMemberListAdapter.notifyItemRangeChanged(0, mMemberEntityList.size(), MemberListAdapter.VOLUME_SHOW);
//            }
//        }, intentFilter);
    }

    private void addMemberEntity(MemberEntity entity) {
        mMemberEntityList.add(0, entity);
        mStringMemberEntityMap.put(entity.getUserId(), entity);
    }

    private int removeMemberEntity(String userId) {
        MemberEntity entity = mStringMemberEntityMap.remove(userId);
        if (entity != null) {
            int i = mMemberEntityList.indexOf(entity);
            mMemberEntityList.remove(entity);
            return i;
        }
        return -1;
    }

    /**
     * 视频item 双击处理
     */
    private void onDoubleClick(View view) {
        if (mMemberEntityList.size() == 1) return;//只有自己

        final MeetingVideoView videoView = (MeetingVideoView) view;
        MemberEntity entity = mStringMemberEntityMap.get(videoView.getMeetingUserId());
        if (entity == null) return;

        final ViewParent viewGroup = videoView.getViewParent();
        if (viewGroup == mContainerFl) {
            entity.setShowOutSide(false);
            mContainerFl.removeView(videoView);
            mContainerFl.setVisibility(View.GONE);
            mShowUserId = "";
            videoView.refreshParent();
        } else if (viewGroup instanceof ViewGroup) {
            entity.setShowOutSide(true);
            mShowUserId = entity.getUserId();
            videoView.detach();
            mContainerFl.setVisibility(View.VISIBLE);
            videoView.addViewToViewGroup(mContainerFl);
        }
    }

    /**
     * 创建视频聊天会议房间，或者进入房间
     */
    private void startCreateOrEnterMeeting() {
        mTRTCMeeting.setDelegate(this);
        mTRTCMeeting.setSelfProfile("mUserName", "mUserAvatar", null);
        createMeeting();
        // 根据外面传入的设置，选择是否打开相应的功能
        mTRTCMeeting.setAudioQuality(TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT);
        mTRTCMeeting.startMicrophone();
        mTRTCMeeting.startCameraPreview(isFrontCamera, mViewVideo.getLocalPreviewView());
        mTRTCMeeting.setSpeaker(isUseSpeaker);
        mTRTCMeeting.enableAudioEvaluation(true);

        notifyStartTime(false);
//        mTimeDisposable = Observable.timer(60, TimeUnit.SECONDS)
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<Long>() {
//                    @Override
//                    public void accept(Long aLong) throws Exception {
//                        mProgressBar.setVisibility(View.GONE);
//                        new AlertDialog().setContent("当前用户无反应，请稍后再试")
//                                .setCancelable(false)
//                                .setSingleBtn(null, (d,w)->finish())
//                                .setTitle("提示").show(getActivity());
//                    }
//                });
    }

    /**
     * 处理 当前用户的视频播放
     */
    private void processSelfVideoPlay(int item) {
        TxLogger.i("---------isShowOutSide "+mMemberEntityList.get(item).isShowOutSide());
        if (mMemberEntityList.get(item).isShowOutSide()) {
            return;
        }
        MeetingVideoView meetingVideoView = mMemberEntityList.get(item).getMeetingVideoView();
        meetingVideoView.refreshParent();
    }

    /**
     * 处理页面中需要展示的item
     * 如果滑动到新的页面，旧的页面所有item需要停止播放
     * 新的页面根据是否打开了video来判断需要播放页面
     *
     * @param fromItem 开始item
     * @param toItem 结尾item
     */
    private void processVideoPlay(int fromItem, int toItem) {
        List<String> oldUserIds = new ArrayList<>();
        List<String> newUserIds = new ArrayList<>();
        List<String> needStopIds = new ArrayList<>();
        List<MemberEntity> newVisibleStream = new ArrayList<>();
        if (mVisibleVideoStreams == null) {
            mVisibleVideoStreams = new ArrayList<>();
        }
        for (int i = fromItem; i <= toItem; i++) {
            newUserIds.add(mMemberEntityList.get(i).getUserId());
            newVisibleStream.add(mMemberEntityList.get(i));
        }
        for (MemberEntity entity : mVisibleVideoStreams) {
            oldUserIds.add(entity.getUserId());
            if (!newUserIds.contains(entity.getUserId())) {
                needStopIds.add(entity.getUserId());
            }
        }
        for (MemberEntity entity : newVisibleStream) {
            if (entity.isShowOutSide()) {
                continue;
            }
            MeetingVideoView meetingVideoView = entity.getMeetingVideoView();
            meetingVideoView.refreshParent();
            if (entity.isNeedFresh()) {
                entity.setNeedFresh(false);
                if (!entity.isMuteVideo() && entity.isVideoAvailable()) {
                    meetingVideoView.setPlaying(true);
                    mTRTCMeeting.startRemoteView(entity.getUserId(), entity.getMeetingVideoView().getPlayVideoView(), null);
                } else {
                    if (meetingVideoView.isPlaying()) {
                        meetingVideoView.setPlaying(false);
                        mTRTCMeeting.stopRemoteView(entity.getUserId(), null);
                    }
                }
                continue;
            }
            if (!oldUserIds.contains(entity.getUserId())) {
                if (!entity.isMuteVideo() && entity.isVideoAvailable()) {
                    if (!meetingVideoView.isPlaying()) {
                        meetingVideoView.setPlaying(true);
                        mTRTCMeeting.startRemoteView(entity.getUserId(), entity.getMeetingVideoView().getPlayVideoView(), null);
                        meetingVideoView.refreshParent();
                    }
                } else {
                    if (meetingVideoView.isPlaying()) {
                        meetingVideoView.setPlaying(false);
                        mTRTCMeeting.stopRemoteView(entity.getUserId(), null);
                    }
                }
            } else {
                if (entity.isMuteVideo() || !entity.isVideoAvailable()) {
                    if (meetingVideoView.isPlaying()) {
                        meetingVideoView.setPlaying(false);
                        mTRTCMeeting.stopRemoteView(entity.getUserId(), null);
                    }
                }
            }
        }
        for (String id : needStopIds) {
            MemberEntity entity = mStringMemberEntityMap.get(id);
            if (entity != null) {
                entity.getMeetingVideoView().setPlayingWithoutSetVisible(false);
            }
            mTRTCMeeting.stopRemoteView(id, null);
        }
        mVisibleVideoStreams = newVisibleStream;
    }

    private void createMeeting() {
        TxLogger.i("createMeeting:", mRoomId);
        mTRTCMeeting.createMeeting(mRoomId, new TRTCMeetingCallback.ActionCallback() {
            @Override
            public void onCallback(int code, String msg) {
                TxLogger.i("createMeeting back:", code, msg);
                if (code == 0) {
                    // 创建房间成功
                    isCreating = true;
                    notifyRoomCreate();
                    //ToastUtil.showMsg("会议创建成功");
                    changeResolution();
//                    HttpClient.create(NotaryApi.class).joinInterviewRoom(mRoomMemberId)
//                            .compose(HttpClient.get())
//                            .subscribe(new HttpCallback<Object>() {
//                                @Override
//                                public void onResponse(Object response) {
//
//                                }
//                            });
                    return;
                }
                isCreating = false;
                // 会议创建不成功，进入会议
                mTRTCMeeting.enterMeeting(mRoomId, new TRTCMeetingCallback.ActionCallback() {
                    @Override
                    public void onCallback(int code, String msg) {
                        if (code != 0) {
                            fail(msg);
                            // 进房失败
//                            ToastUtil.showMsg(msg);
//                            finish();
                        }
                        changeResolution();
                    }
                });
            }
        });
    }

    private void exitMeetingConfirm() {
        if(mTRTCMeeting == null) return;
        mTRTCMeeting.logout(null);
        if (isCreating) {
            mTRTCMeeting.destroyMeeting(mRoomId, null);
        } else {
            mTRTCMeeting.leaveMeeting(null);
        }
    }

    private void changeResolution() {
        //使用流畅模式，不使用高清
//        if (mVideoQuality == CreateMeetingActivity.VIDEO_QUALITY_HD) {
//            TRTCCloudDef.TRTCNetworkQosParam qosParam = new TRTCCloudDef.TRTCNetworkQosParam();
//            qosParam.preference = TRTCCloudDef.TRTC_VIDEO_QOS_PREFERENCE_CLEAR;
//            mTRTCMeeting.setNetworkQosParam(qosParam);
//            if (mMemberEntityList.size() <= 2) {
//                mTRTCMeeting.setVideoResolution(TRTCCloudDef.TRTC_VIDEO_RESOLUTION_960_540);
//                mTRTCMeeting.setVideoFps(15);
//                mTRTCMeeting.setVideoBitrate(1300);
//            } else if (mMemberEntityList.size() < 4) {
//                mTRTCMeeting.setVideoResolution(TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360);
//                mTRTCMeeting.setVideoFps(15);
//                mTRTCMeeting.setVideoBitrate(800);
//            } else {
//                mTRTCMeeting.setVideoResolution(TRTCCloudDef.TRTC_VIDEO_RESOLUTION_480_270);
//                mTRTCMeeting.setVideoFps(15);
//                mTRTCMeeting.setVideoBitrate(400);
//            }
//        } else {
        TRTCCloudDef.TRTCNetworkQosParam qosParam = new TRTCCloudDef.TRTCNetworkQosParam();
        qosParam.preference = TRTCCloudDef.TRTC_VIDEO_QOS_PREFERENCE_SMOOTH;
        mTRTCMeeting.setNetworkQosParam(qosParam);
        if (mMemberEntityList.size() < 5) {
            // 包括自己，一共四个人，选择360p分辨率
            mTRTCMeeting.setVideoResolution(TRTCCloudDef.TRTC_VIDEO_RESOLUTION_640_360);
            mTRTCMeeting.setVideoFps(15);
            mTRTCMeeting.setVideoBitrate(700);
        } else {
            mTRTCMeeting.setVideoResolution(TRTCCloudDef.TRTC_VIDEO_RESOLUTION_480_270);
            mTRTCMeeting.setVideoFps(15);
            mTRTCMeeting.setVideoBitrate(350);
        }
//        }
    }

    @Override
    public void onError(int code, String message) {
        TxLogger.e(code, message);
        toast(message);
        //ToastUtil.showMsg(message);
    }

    @Override
    public void onRoomDestroy(String roomId) {
        if (String.valueOf(mRoomId).equals(roomId)) {
            fail("创建者已结束会议");
//            ToastUtil.showMsg("创建者已结束会议");
//            finish();
        }
    }

    @Override
    public void onNetworkQuality(TRTCCloudDef.TRTCQuality localQuality, List<TRTCCloudDef.TRTCQuality> remoteQuality) {
        TxLogger.d("onNetworkQuality: ");
        matchQuality(localQuality, mStringMemberEntityMap.get(mUserId));
        for (TRTCCloudDef.TRTCQuality quality : remoteQuality) {
            matchQuality(quality, mStringMemberEntityMap.get(quality.userId));
        }
    }

    private void matchQuality(TRTCCloudDef.TRTCQuality trtcQuality, MemberEntity entity) {
        if (entity == null) {
            return;
        }
        int oldQulity = entity.getQuality();
        switch (trtcQuality.quality) {
            case TRTCCloudDef.TRTC_QUALITY_Excellent:
            case TRTCCloudDef.TRTC_QUALITY_Good:
                entity.setQuality(MemberEntity.QUALITY_GOOD);
                break;
            case TRTCCloudDef.TRTC_QUALITY_Vbad:
            case TRTCCloudDef.TRTC_QUALITY_Down:
                entity.setQuality(MemberEntity.QUALITY_BAD);
                break;
            default:
                entity.setQuality(MemberEntity.QUALITY_NORMAL);
                break;
        }
        if (oldQulity != entity.getQuality()) {
            mMemberListAdapter.notifyItemChanged(mMemberEntityList.indexOf(entity), MemberListAdapter.QUALITY);
        }
    }

    @Override
    public void onUserVolumeUpdate(String userId, int volume) {
        if (!mAudioVolumeEvaluation) {
            return;
        }
        if (userId == null) {
            userId = mUserId;
        }
        MemberEntity memberEntity = mStringMemberEntityMap.get(userId);
        if (memberEntity != null) {
            memberEntity.setAudioVolume(volume);
            mMemberListAdapter.notifyItemChanged(mMemberEntityList.indexOf(memberEntity), MemberListAdapter.VOLUME);
        }
    }

    @Override
    public void onUserEnterRoom(String userId) {
        TxLogger.e("txLiveChat user enter room", userId,"member size",mMemberEntityList.size());
        if(mMemberEntityList.size() == 1) { //只有本人
//            mTimeDisposable = RxBus.release(mTimeDisposable);
//            mProgressBar.setVisibility(View.GONE);
//            startTime();
            notifyStartTime(true);
        }
        final MemberEntity     entity           = new MemberEntity();
        final MeetingVideoView meetingVideoView = new MeetingVideoView(getContext());
        meetingVideoView.setMeetingUserId(userId);
        meetingVideoView.setNeedAttach(false);
        meetingVideoView.setListener(mMeetingViewClick);
        entity.setUserId(userId);
        entity.setMeetingVideoView(meetingVideoView);
        entity.setMuteAudio(mIsUserEnterMuteAudio);
        entity.setMuteVideo(false);
        entity.setVideoAvailable(false);
        entity.setAudioAvailable(false);
        entity.setShowAudioEvaluation(mAudioVolumeEvaluation);
        addMemberEntity(entity);
        changeResolution();
        mMemberListAdapter.notifyItemInserted(0); //最后进入的插入到第一条
        mTRTCMeeting.muteRemoteAudio(userId, mIsUserEnterMuteAudio);
        mTRTCMeeting.getUserInfo(userId, new TRTCMeetingCallback.UserListCallback() {
            @Override
            public void onCallback(int code, String msg, List<TRTCMeetingDef.UserInfo> list) {
                if (code == 0 && list != null && list.size() != 0) {
                    entity.setUserName(list.get(0).userName);
                    entity.setUserAvatar(list.get(0).userAvatar);
                    mMemberListAdapter.notifyItemChanged(mMemberEntityList.indexOf(entity));
                }
            }
        });
    }

    @Override
    public void onUserLeaveRoom(String userId) {
        if (mShowUserId.equals(userId)) {
            mShowUserId = "";
            mContainerFl.removeAllViews();
            mContainerFl.setVisibility(View.GONE);
        }
        int index = removeMemberEntity(userId);
        changeResolution();
        if (index >= 0) {
            mMemberListAdapter.notifyItemRemoved(index);
        }
    }

    @Override
    public void onUserVideoAvailable(String userId, boolean available) {
        TxLogger.e("txLiveChat onUserVideoAvailable", userId,available);
        MemberEntity entity = mStringMemberEntityMap.get(userId);
        if (!available && mShowUserId.equals(userId)) {
            mShowUserId = "";
            mContainerFl.removeAllViews();
            mContainerFl.setVisibility(View.GONE);
            if(entity != null) {
                entity.setShowOutSide(false);
            }
        }
        if (entity != null) {
            entity.setNeedFresh(true);
            entity.setVideoAvailable(available);
            entity.getMeetingVideoView().setNeedAttach(available);
            mMemberListAdapter.notifyItemChanged(mMemberEntityList.indexOf(entity));
        }
    }

    @Override
    public void onUserAudioAvailable(String userId, boolean available) {
        MemberEntity entity = mStringMemberEntityMap.get(userId);
        if (entity != null) {
            entity.setAudioAvailable(available);
            //界面暂时没有变更
        }
    }


    /**
     * 通知会议创建成功，请求后端告知 mRoomMemberId进入房间
     */
    private void notifyRoomCreate(){
        callback(TxConstant.ChatMethod.Back.notifyRoomCreate,"会议创建成功");
    }

    /**
     * 开始计时，
     * @param intoRoom 是否进入房间，false代表尝试进入房间，可以计时1分钟后提示进入房间失败，关闭页面，如果收到true则停止该计时；
     *                 true代表成功进入房间，计时30分钟后，退出房间
     */
    private void notifyStartTime(boolean intoRoom) {
        Map<String,Object> map = new HashMap<>();
        map.put(TxConstant.ChatMethod.Key.intoRoom,intoRoom);
        map.put(TxConstant.ChatMethod.Key.timeCount,intoRoom? 60*30 : 60);
        callback(TxConstant.ChatMethod.Back.startTime, map);
    }

    private void toast(String msg){
        callback(TxConstant.ChatMethod.Back.toast,msg);
    }

    private void fail(String msg){
        callback(TxConstant.ChatMethod.Back.fail,msg);
    }

    private void callback(String name,Object data){
        if(mOnChatCallback != null){
            mOnChatCallback.callback(name,data);
        }
    }
    /**
     * 设置 回调给flutter事件
     */
    public void setOnChatCallback(ChatManager.OnChatCallback callback) {
        this.mOnChatCallback = callback;
    }
}
